/***************************************************************************
 *   Copyright (C) 2008 by Ryszard Krol   *
 *   rysiek.krol@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/


#include <QtGui>
#include "picturemanager.h"
#include "imagereader.h"
#include "renamedialog.h"
#include "updateiconevent.h"
#include "picturelistwidgetitem.h"
#include "imageloadedevent.h"
#include "imageloader.h"
#include "updatestatusbarevent.h"
#include "commentdialog.h"
#include "propertydialog.h"
#include "fileoperationshandler.h"
#include "progressdialogevent.h"
#include "progressbardialogs.h"

#include <QCloseEvent>
#include <QFileDialog>
#include <QListWidget>
#include <QDir>
#include <QMenu>
#include <QPixmap>
#include <QMutex>
#include <QWidget>
#include <QSplitter>
#include <QTreeView>
#include <QList>
#include <QDirModel>
#include <QStyle>
#include <QScrollArea>
#include <QKeyEvent>


/**
* Class constructor
*/
PictureManager::PictureManager(QStyle *styl)
{
	this->itsProperty = new Property();
	this->curDir = new QDir(this->itsProperty->getPictureDir());
        this->oldDir = new QDir(this->itsProperty->getPictureDir());
	initializeGUI(styl);
	this->switchGuiToBrowserMode();
}

/**
* Class constructor
*/
PictureManager::PictureManager(QStyle * styl, QString filePath)
{
	
        if (filePath.endsWith("\n")) filePath.chop(2);
        if (filePath.endsWith("\t")) filePath.chop(1);
        if (filePath.endsWith(" ")) filePath.chop(1);
        QFileInfo *pliczek = new QFileInfo(filePath);
        this->itsProperty = new Property();
        if (pliczek->exists()) {
                this->curDir = new QDir(pliczek->dir());
                this->oldDir = new QDir(pliczek->dir());
                initializeGUI(styl);
                this->switchGuiToPresentationMode(pliczek);
        } else {
                this->curDir = new QDir();
                this->oldDir = new QDir();
                initializeGUI(styl);
                this->switchGuiToBrowserMode();
        }
        delete pliczek;
}
/**
* Build GUI
*/

void PictureManager::initializeGUI(QStyle * styl)
{
	
	
        this->setStyl(styl);
        this->buildBrowserWidget();
        //tworzenie glownego okna
        this->setCentralWidget ( this->browserWidget);
        this->itsReader =  new ImageReader ( this, this->curDir );
        this->isPresentationMode = false;
	
	this->browserToolBar = this->addToolBar ( tr ( "BrowserToolBar" ) );
	this->presentationToolBar = this->addToolBar ( tr ( "PresentationToolBar" ) );
	this->sortingToolBar = this->addToolBar(tr("SortingToolBar"));
	this->sortingCombo = new QComboBox();
	this->sortingCombo->addItem(tr("Sort by comment date"));
	this->sortingCombo->addItem(tr("Sort by file name"));
	this->sortingCombo->setCurrentIndex(this->itsProperty->getSortMethod());
	this->sortingMethodChangedAct = this->sortingToolBar->addWidget(this->sortingCombo);
	
        createActions();
        createMenus();
        createToolBars();
        createStatusBar();
	this->move(this->itsProperty->getWindowPosition());
	this->resize(this->itsProperty->getWindowSize());
        //Ustawianie Tytulu

        this->setWindowTitle(tr("AliceViewer: ") + this->curDir->absolutePath() );
        this->itsLoader = new ImageLoader(this);
	this->fullScreen = false;
	this->progressBarDialogs = new ProgressBarDialogs();
	
}

/**
 * Building About dialog
 */
void PictureManager::about()
{

        QMessageBox::about ( this, tr ( "About Application" ),
                             tr("Multi-platform picture manager" ) );

}
/**
 * Creates Actions
 */
void PictureManager::createActions()
{

        renameAct = new QAction ( tr ( "&Rename" ), this );
        renameAct->setShortcut ( tr ( "Ctrl+R" ) );
        renameAct->setStatusTip ( tr ( "Change file name" ) );
        connect ( renameAct, SIGNAL ( triggered() ), this, SLOT ( renameDialog() ) );

        exitAct = new QAction ( tr ( "E&xit" ), this );
        exitAct->setShortcut ( tr ( "Ctrl+Q" ) );
        exitAct->setStatusTip ( tr ( "Exit the application" ) );
        connect ( exitAct, SIGNAL ( triggered() ), this, SLOT ( close() ) );

        aboutAct = new QAction ( tr ( "&About" ), this );
        aboutAct->setStatusTip ( tr ( "Show the application's About box" ) );
        connect ( aboutAct, SIGNAL ( triggered() ), this, SLOT ( about() ) );

        aboutQtAct = new QAction ( tr ( "About &Qt" ), this );
        aboutQtAct->setStatusTip ( tr ( "Show the Qt library's About box" ) );
        connect ( aboutQtAct, SIGNAL ( triggered() ), qApp, SLOT ( aboutQt() ) );

        connect (this->treeWidget, SIGNAL (clicked(const QModelIndex & )) , this, SLOT (treeClicked(const QModelIndex & )));
        connect ( this->listWidget, SIGNAL ( itemDoubleClicked ( QListWidgetItem * ) ), this, SLOT ( listClicked ( QListWidgetItem * ) ) );

        closePresentaionAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_DialogCloseButton), tr ( "&Close" ), this );
        closePresentaionAct->setStatusTip ( tr ( "Close Image" ) );
        connect ( closePresentaionAct, SIGNAL ( triggered() ), this, SLOT ( switchGuiToBrowserMode() ) );

        displayNextImageAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_ArrowRight),tr ( "&Next" ), this );
        displayNextImageAct->setStatusTip ( tr ( "Next Image" ) );
        connect ( displayNextImageAct, SIGNAL ( triggered() ), this, SLOT ( displayNextImage() ) );

        displayPreviousImageAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_ArrowLeft),tr ( "&Previous" ), this );
        displayPreviousImageAct->setStatusTip ( tr ( "Previouse Image" ) );
        connect ( displayPreviousImageAct, SIGNAL ( triggered() ), this, SLOT ( displayPreviousImage() ) );

        goBackAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_ArrowBack),tr ( "&Back" ), this );
        goBackAct->setStatusTip ( tr ( "Go to previous directory" ) );
        connect ( goBackAct, SIGNAL ( triggered() ), this, SLOT ( goBackSlot() ) );

        this->goUpAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_ArrowUp),tr ( "&Up" ), this );
        this->goUpAct->setStatusTip ( tr ( "Go to upper directory" ) );
        connect ( this->goUpAct, SIGNAL ( triggered() ), this, SLOT ( goUpSlot() ) );

        this->reLoadBrowserAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_BrowserReload),tr ( "&Reload" ), this );
        this->reLoadBrowserAct->setStatusTip ( tr ( "Reload view" ) );
        connect ( this->reLoadBrowserAct, SIGNAL ( triggered() ), this, SLOT ( reLoadBrowserSlot() ) );

        this->goToFullScreenAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_ComputerIcon),tr ( "&Full Screen" ), this );
        this->goToFullScreenAct->setStatusTip ( tr ( "Show picture in Full Screen" ) );
        connect ( this->goToFullScreenAct, SIGNAL ( triggered() ), this, SLOT ( fullScreenSwichSlot() ) );
        
        this->commentEditAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_ComputerIcon),tr ( "&Edit Comment" ), this );
        this->commentEditAct->setStatusTip ( tr ( "Edit Picture Comments" ) );
        connect ( this->commentEditAct, SIGNAL ( triggered() ), this, SLOT ( editComment() ) );

        this->commentRemoveAct = new QAction (this->getStyl()->standardIcon(QStyle::SP_TrashIcon),tr ( "&Remove comment" ), this );
        this->commentRemoveAct->setStatusTip ( tr ( "Remove picture's comment" ) );
        connect ( this->commentRemoveAct, SIGNAL ( triggered() ), this, SLOT ( removeCommentSlot() ) );
        
        this->PropertyDialogOpenAct = new QAction (tr ( "&Properties" ), this );
        this->PropertyDialogOpenAct->setStatusTip ( tr ( "Application Settings" ) );
        connect ( this->PropertyDialogOpenAct, SIGNAL ( triggered() ), this, SLOT ( PropertyDialogOpenSlot() ) );
	
	this->removeFilesAct = new QAction (tr ( "&Delete" ), this );
        this->removeFilesAct->setStatusTip ( tr ( "Delete selected files" ) );
        connect ( this->removeFilesAct, SIGNAL ( triggered() ), this, SLOT ( deleteFilesSlot() ) );
	
	connect ( this->sortingCombo, SIGNAL ( currentIndexChanged ( int ) ), this, SLOT ( reLoadBrowserSlot() ) );

	this->copyFilesAct = new QAction (tr ( "&Copy" ), this );
        this->copyFilesAct->setStatusTip ( tr ( "Copy selected files" ) );
        connect ( this->copyFilesAct, SIGNAL ( triggered() ), this, SLOT ( copyFilesSlot() ) );
        
        this->moveFilesAct = new QAction (tr ( "&Move" ), this );
        this->moveFilesAct->setStatusTip ( tr ( "Move selected files" ) );
        connect ( this->moveFilesAct, SIGNAL ( triggered() ), this, SLOT ( moveFilesSlot() ) );
        
        this->makeDirectoryAct = new QAction (tr ( "&Make Directory" ), this );
        this->makeDirectoryAct->setStatusTip ( tr ( "Make New Direcotry" ) );
        connect ( this->makeDirectoryAct, SIGNAL ( triggered() ), this, SLOT ( makeDirectorySlot() ) );
        
}

/**
 * Building Menus
 */
void PictureManager::createMenus()
{
        fileMenu = menuBar()->addMenu ( tr ( "&File" ) );
        fileMenu->addAction ( exitAct );

        editMenu = menuBar()->addMenu ( tr ( "&Edit" ) );
        editMenu->addAction ( renameAct );
        editMenu->addSeparator();
        editMenu->addAction(PropertyDialogOpenAct);
        menuBar()->addSeparator();

        helpMenu = menuBar()->addMenu ( tr ( "&Help" ) );
        helpMenu->addAction ( aboutAct );
        helpMenu->addAction ( aboutQtAct );

        contextMenu = new QMenu ( this->listWidget );
        contextMenu->addAction ( this->renameAct );
        contextMenu->addAction ( this->removeFilesAct);
        contextMenu->addAction ( this->copyFilesAct );
        contextMenu->addAction (this->moveFilesAct);
        contextMenu->addAction (this->makeDirectoryAct);
        contextMenu->addSeparator();
        contextMenu->addAction ( commentEditAct );
        contextMenu->addAction ( commentRemoveAct );
}

/**
 * Building Tool Bars
 */
void PictureManager::createToolBars()
{
        this->browserToolBar->addAction(this->goBackAct);
        this->browserToolBar->addAction(this->goUpAct);
	this->browserToolBar->addAction(this->reLoadBrowserAct);
	this->browserToolBar->setVisible(false);
        this->presentationToolBar->addAction(this->closePresentaionAct);
        this->presentationToolBar->addSeparator();
        this->presentationToolBar->addAction(this->displayPreviousImageAct);
        this->presentationToolBar->addAction(this->displayNextImageAct);
	this->presentationToolBar->addAction(this->goToFullScreenAct);
	this->sortingToolBar->setVisible(true);
        presentationToolBar->setVisible(false);
}

/**
 * Building Status Bar
 */
void PictureManager::createStatusBar()
{
        statusBar()->showMessage ( tr ( "Ready" ) );
}

/**
 * Class Destructor
 */
PictureManager::~PictureManager()
{
        delete this->curDir;
	delete this->oldDir;
}

/**
 * Returns ListWidget
 */
QListWidget* PictureManager::getListWidget()
{
        return this->listWidget;
}

/**
 * Handles Custom Events
 */
void PictureManager::customEvent ( QEvent *event )
{
        switch (event->type()) {
        case ViewerEvent::ListRefreshNeeded:
                this->listWidget->update();
                break;
        case ViewerEvent::UpdateIcon:
                if ( this->listWidget->count() >0 ) {
                        UpdateIconEvent *updateEvent = dynamic_cast<UpdateIconEvent*> (event );
                        if (updateEvent->getItem()->getFile().isDir()) {
                                updateEvent->getItem()->setIcon(this->getStyl()->standardIcon(QStyle::SP_DirIcon));
                        } else {
                                updateEvent->getItem()->setIcon (QPixmap::fromImage(updateEvent->getIcon()));
                        }
                }
                break;
        case ViewerEvent::iconGenerationCompleateEvent:
                this->listWidget->clear();
                this->itsReader->setDir(this->curDir);
                this->itsReader->readDirCondition.wakeAll();
                this->setWindowTitle(tr("AliceViewer: ") + this->curDir->absolutePath() );
                break;
        case ViewerEvent::LoadedImageEvent: {
                ImageLoadedEvent *imageEvent = dynamic_cast<ImageLoadedEvent*> (event);
		
		this->presentationWidget->setToolTip(this->listWidget->item(imageEvent->getImageIndex())->toolTip());
                this->displayImage(QPixmap::fromImage(imageEvent->getImage()));
        }
        break;
        case ViewerEvent::UpdateStatusBar: {
                UpdateStatusBarEvent *updateEvent = dynamic_cast<UpdateStatusBarEvent*>(event);
                this->statusBar()->showMessage ( updateEvent->getStatus() );
        }
        break;
        case ViewerEvent::ForceReload: {
        	if(this->isPresentationMode){
        		this->displayCorrectImage();
        	} else {
        		this->reLoadBrowserSlot();
        	}
        	break;
        }
        case ViewerEvent::ProgressDialogUpdate: {
        	ProgressDialogEvent *updateEvent = dynamic_cast<ProgressDialogEvent*>(event);
        	this->progressBarDialogs->attendValue(updateEvent);
     		}
        break;
        default:
                QMainWindow ( event );
                break;
        }
}

/**
 * Manage listClicked event
 */
void PictureManager::listClicked ( QListWidgetItem * item )
{
        PictureListWidgetItem *pItem= dynamic_cast<PictureListWidgetItem*>(item);

        QFileInfo *fileInfo = new QFileInfo ( pItem->getFile() );
        if ( fileInfo->isDir() ) {
                *this->oldDir = *this->curDir;
                if ( fileInfo->fileName() == ".." ) {
                        QModelIndex index=(dynamic_cast<QDirModel*>(this->treeWidget->model()))->index( curDir->path());
                        this->treeWidget->collapse(index);
                        curDir->cdUp();
                } else {
                        curDir->cd ( fileInfo->fileName() );
                        QModelIndex index=(dynamic_cast<QDirModel*>(this->treeWidget->model()))->index( curDir->path());
                        this->treeWidget->expand(index);

                }

                QModelIndex index=(dynamic_cast<QDirModel*>(this->treeWidget->model()))->index( curDir->path());
                this->treeWidget->setCurrentIndex(index);

                if (this->itsReader->active()) {
                        this->itsReader->setIsActive(false);
                } else {
                        this->listWidget->clear();
                        this->itsReader->setDir(this->curDir);
                        this->itsReader->readDirCondition.wakeAll();
                        this->setWindowTitle(tr("AliceViewer: ") + this->curDir->absolutePath() );
                }
        } else {
                this->switchGuiToPresentationMode(fileInfo);
        }
        delete fileInfo;
}

/**
 * Displays Context Menu
 */
void PictureManager::contextMenuEvent ( QContextMenuEvent *event )
{
	if(!this->getIsPresentationMode() && this->listWidget->underMouse()) contextMenu->popup ( event->globalPos() );

}

/**
 * Manage TreeClickedEvent
 */
void PictureManager::treeClicked( const QModelIndex & index )
{
        QFileInfo fileInfo =(dynamic_cast<QDirModel*>(this->treeWidget->model()))->fileInfo(index);
        if ( fileInfo.isDir() ) {
                *this->oldDir = *this->curDir;
                if (fileInfo.absoluteFilePath () != curDir->absolutePath () ) {
                        curDir->cd ( fileInfo.absoluteFilePath () );
                        if (this->itsReader->active()) {
                                this->itsReader->setIsActive(false);
                        } else {
                                this->itsReader->setIsActive(false);
                                this->listWidget->clear();
                                this->itsReader->setDir(this->curDir);
                                this->itsReader->readDirCondition.wakeAll();
                                this->setWindowTitle(tr("AliceViewer: ") + this->curDir->absolutePath() );
                        }
                }
        }
}

/**
 * Renameing files
 */
void PictureManager::renameDialog()
{
        QString newFileName;
        RenameDialog dialog ( this );
        if ( dialog.exec() ) {
               new FileOperationsHandler(this, FileOperationsHandler::Rename,this->fillFileList(), dialog.getText());
        }
}
/**
 * Returns application style
 */
QStyle * PictureManager::getStyl()
{
        return styl;
}
/**
 * Sets application style
 */
void PictureManager::setStyl( QStyle *theValue)
{
        styl = theValue;
}
/**
* Builds main widget
*/
void PictureManager::buildBrowserWidget()
{
        //Tworzenie Drzewka
        QStringList *filters = new QStringList();
        *filters << "[A-Z, A-Z, 0-9]*" ;
        QDirModel *model = new QDirModel ( *filters, QDir::Dirs, QDir::Name );
        this->treeWidget = new QTreeView();
        this->treeWidget->setModel ( model );
        QDir w = *this->curDir;
        QModelIndex index = model->index ( w.path() );
        this->treeWidget->setColumnHidden(1, true);
        this->treeWidget->setColumnHidden(2, true);
        this->treeWidget->setColumnHidden(3, true);
        this->treeWidget->setCurrentIndex(index);
	this->treeWidget->setVisible(false);

        while ( w.cdUp() ) {

                QModelIndex index = model->index ( w.path() );
                this->treeWidget->expand ( index );
        }
        // Tworzenie splittera
        this->browserWidget = new QSplitter();
        //tworzenie Okna ikon
        this->listWidget = new QListWidget();
        this->listWidget->setViewMode ( QListView::IconMode );
        this->listWidget->setIconSize ( QSize ( 100, 100 ) );
        this->listWidget->setResizeMode ( QListView::Adjust );
        this->listWidget->setSpacing ( 20 );
        this->listWidget->setGridSize ( QSize ( 150, 180 ) );
        this->listWidget->setMovement ( QListView::Snap );
        this->listWidget->setSelectionMode ( QAbstractItemView::ExtendedSelection );
	this->listWidget->setVisible(false);

        this->scrollArea = new QScrollArea();
        this->scrollArea->setVisible(false);
        this->scrollArea->setWidgetResizable(true);
        this->presentationWidget = new QLabel(tr ("Loading Image..."));
        this->presentationWidget->setAlignment(Qt::AlignCenter);
	this->presentationWidget->setAutoFillBackground(true);

        this->scrollArea->setWidget(this->presentationWidget);
        //Dodawanie drzewa i okna ikon do kontenera
        this->browserWidget->addWidget(this->treeWidget);
        this->browserWidget->addWidget(this->listWidget);
        this->browserWidget->addWidget(this->scrollArea);
        this->browserWidget->setStretchFactor(1,3);

        delete filters;
}

/**
 * Switches GUI to Presentation mode
 */
void PictureManager::switchGuiToPresentationMode(QFileInfo *fileInfo)
{
        this->loadImage(this->findItem(fileInfo));
	this->presentationWidget->setToolTip(this->listWidget->item(this->findItem(fileInfo))->toolTip());
        this->treeWidget->setVisible(false);
        this->listWidget->setVisible(false);
        this->browserToolBar->setVisible(false);
	this->sortingToolBar->setVisible(false);
	this->sortingMethodChangedAct->setVisible(false);
        this->presentationToolBar->setVisible(true);
        this->scrollArea->setVisible(true);
	this->setIsPresentationMode(true);
}

/**
 * Switches GUI to Browser mode
 */
void PictureManager::switchGuiToBrowserMode()
{
        this->scrollArea->setVisible(false);
        this->presentationToolBar->setVisible(false);
        this->browserToolBar->setVisible(true);
        this->treeWidget->setVisible(true);
        this->listWidget->setVisible(true);
	this->sortingToolBar->setVisible(true);
	this->sortingMethodChangedAct->setVisible(true);
	this->sortingMethodChangedAct->setEnabled(true);
	this->setIsPresentationMode(false);
}

/**
 * Display image from fileInfo via presentationWidget
 */
void PictureManager::displayImage(QPixmap pixmap)
{
        QSize size = this->browserWidget->size();
        if (size.width()>pixmap.size().width() && size.height()>pixmap.size().height()) {
        	this->presentationWidget->setPixmap(pixmap);
        } else {
                if (size.height()>size.width()) {
                        size.scale(size.width(),size.height()-5, Qt::KeepAspectRatio);
                } else {
                        size.scale(size.width()-5,size.height()-5, Qt::KeepAspectRatio);
                }
                this->presentationWidget->setPixmap(pixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation));
        }
}

/**
 * Display Next image in presentationWidget
 */
void PictureManager::displayNextImage()
{
        this->displayNextImage(false);
}

/**
 * Display Next image in presentationWidget
 */
void PictureManager::displayNextImage(bool reloadLoader)
{
	PictureListWidgetItem *item;
        int i = this->itsLoader->getCurrentIndex();
        if (++i<this->getListWidget()->count()) {
                this->itsLoader->setCurrentAction(ImageLoader::GetNext);
                if (reloadLoader) this->itsLoader->setCurrentAction(ImageLoader::GetNextAndReload);
                this->itsLoader->setGoToSleepFalse();
                this->itsLoader->newActionCondition.wakeAll();
		item = dynamic_cast<PictureListWidgetItem*> ( this->getListWidget()->item(i));
                this->getListWidget()->clearSelection();
                item->setSelected(true);
        } 
}


void PictureManager::displayCorrectImage()
{
        int i =this->itsLoader->getCurrentIndex();
        PictureListWidgetItem *item = dynamic_cast<PictureListWidgetItem*> ( this->getListWidget()->item(i));
        delete item;
        this->getListWidget()->update();
        if (i>=this->getListWidget()->count()) {
                this->displayPreviousImage();
        } else if (++i<this->getListWidget()->count()) {
                this->displayNextImage(true);
        }
}

/**
 * Display Previous image in presentationWidget
 */
void PictureManager::displayPreviousImage()
{
        PictureListWidgetItem *item;
        int i = this->itsLoader->getCurrentIndex();
        if (--i>=0) {
                item = dynamic_cast<PictureListWidgetItem*> ( this->getListWidget()->item(i));
                if (!item->getFile().isDir()) {
                        this->itsLoader->setCurrentAction(ImageLoader::GetPrevious);
                        this->itsLoader->setGoToSleepFalse();
                        this->itsLoader->newActionCondition.wakeAll();
                        this->getListWidget()->clearSelection();
                        item->setSelected(true);
                }
        }
}

/**
* Returns index position in ListWidget of file in fileinfo parameter
*/
int PictureManager::findItem(QFileInfo * fileInfo)
{
        for (int i = 0; i<this->listWidget->count(); i++) {
                PictureListWidgetItem *item = dynamic_cast<PictureListWidgetItem*> ( this->getListWidget()->item(i));
                if (item->getFile() == fileInfo->filePath())return i;
        }
        return -1;
}

/**
* Sets new Index in Loader Thread and wakes it
*/
void PictureManager::loadImage(int index)
{
        this->itsLoader->setCurrentAction(ImageLoader::GetIndex);
        this->itsLoader->setCurrentIndex(index);
        this->itsLoader->setGoToSleepFalse();
        this->itsLoader->newActionCondition.wakeAll();
}

/**
* Goes to Presentation Widget
*/
QLabel* PictureManager::getPresentationWidget() const
{
        return presentationWidget;
}

/**
* Goes to previous directory
*/
void PictureManager::goBackSlot()
{
        if (this->curDir!=this->oldDir) {
                QDir tmp = *this->curDir;
                *this->curDir = *this->oldDir;
                *this->oldDir = tmp;
                this->reLoadBrowserSlot();
        }
}

/**
* Goes to upper directory
*/
void PictureManager::goUpSlot()
{
        *this->oldDir = *this->curDir;
        curDir->cdUp();
        QModelIndex index=(dynamic_cast<QDirModel*>(this->treeWidget->model()))->index( curDir->path());
        this->treeWidget->collapse(index);
        this->treeWidget->setCurrentIndex(index);
        if (this->itsReader->active()) {
                this->itsReader->setIsActive(false);
        } else {
                this->itsReader->setIsActive(false);
                this->listWidget->clear();
                this->itsReader->setDir(this->curDir);
                this->itsReader->readDirCondition.wakeAll();
                this->setWindowTitle(tr("AliceViewer: ") + this->curDir->absolutePath() );
        }
}

/**
* Reloads Browser view's
*/
void PictureManager::reLoadBrowserSlot()
{
        QDirModel *index=dynamic_cast<QDirModel*>(this->treeWidget->model());
        index->refresh();
        this->itsReader->setIsActive(false);
        this->listWidget->clear();
        this->itsReader->setDir(this->curDir);
        this->itsReader->readDirCondition.wakeAll();
        this->setWindowTitle(tr("AliceViewer: ") + this->curDir->absolutePath() );
}

/**
* Switching to full screen and to normal view
*/
void PictureManager::fullScreenSwichSlot()
{
        if (getIsPresentationMode()) {
                if (this->fullScreen) {
			this->presentationWidget->setPalette(this->palette());
                        this->showNormal();
                        this->menuBar()->setVisible(true);
                        this->presentationToolBar->setVisible(true);
                        this->statusBar()->setVisible(true);
                        this->fullScreen = false;
                } else {
                        QPalette newPalette = palette();
                        newPalette.setColor(QPalette::Active, QPalette::Window,Qt::black);
                        newPalette.setColor(QPalette::Inactive, QPalette::Window,Qt::black);
			this->presentationWidget->setPalette(newPalette);
                        this->menuBar()->setVisible(false);
                        this->presentationToolBar->setVisible(false);
                        this->statusBar()->setVisible(false);
			this->showFullScreen();
                        this->fullScreen = true;
                }
        }
}

/**
* Handles KeyPressed Event
*/
void PictureManager::keyPressEvent(QKeyEvent * event)
{
        if (getIsPresentationMode()) {
                switch (event->key()) {
                case Qt::Key_F :
                        this->fullScreenSwichSlot();
                        break;
                case Qt::Key_Space :
                case Qt::Key_Return :
                case Qt::Key_Enter :
                        this->displayNextImage();
                        break;
                case Qt::Key_Backspace:
                        this->displayPreviousImage();
                        break;
                case Qt::Key_Delete :
                        this->deleteFilesSlot();
                        break;
                }
        } else {
                switch (event->key()) {
                case Qt::Key_Delete :
                        this->deleteFilesSlot();
                }
        }
}

/**
* Handles Resize Event
*/
void PictureManager::resizeEvent(QResizeEvent * event)
{
        if (getIsPresentationMode()) {
                this->itsLoader->setCurrentAction(ImageLoader::GetCurrent);
                this->itsLoader->setGoToSleepFalse();
                this->itsLoader->newActionCondition.wakeAll();
        } else {
         event->accept();
        }
}

/**
* Returns if program is in Presentation Mode
*/
bool PictureManager::getIsPresentationMode() const
{
        return isPresentationMode;
}

/**
* Sets isPresentationMode Variable
*/
void PictureManager::setIsPresentationMode(bool theValue)
{
        isPresentationMode = theValue;
}

/**
* Handles MousePressed Event
*/
void PictureManager::mousePressEvent(QMouseEvent * event)
{
        if (getIsPresentationMode()) {
                switch (event->button()) {
                case Qt::LeftButton:
                        this->displayNextImage();
                        break;
                case Qt::RightButton:
                        this->displayPreviousImage();
                        break;
                default:
                        break;
                }
        }
}

/**
* Handles Wheel Event
*/
void PictureManager::wheelEvent(QWheelEvent * event)
{
        if (this->getIsPresentationMode()) {
                if (event->delta()>0 && event->delta()>15) {
                        this->displayPreviousImage();
                } else if (event->delta()<0 && event->delta()<-15) {
                        this->displayNextImage();
                }
        } else {
                event->ignore();
        }
}
/**
* Opens comment Edit Window
*/
void PictureManager::editComment()
{
        CommentDialog dialog (this->listWidget);
        if (dialog.exec()) {
                this->reLoadBrowserSlot();
        }
}

/**
* Removes comment from selected Pictures
*/
void PictureManager::removeCommentSlot()
{
         QMessageBox msgBox;
         msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
         msgBox.setText(tr("Are you sure to remove comments from selected pictures?"));
         msgBox.setWindowTitle("Removing comments...");
         msgBox.setIcon(QMessageBox::Question);
        if (msgBox.exec()==QMessageBox::Yes) {
        	this->itsReader->setIsActive(false);
    		new FileOperationsHandler(this, FileOperationsHandler::RemoveComments, this->fillFileList());
        }
}
/**
* Manages closeEvent
*/
void PictureManager::closeEvent(QCloseEvent * event )
{
	this->itsProperty->setWindowSize(this->size());
	this->itsProperty->setWindowPosition(this->pos());
	this->itsProperty->saveProperty();
        event->accept();
}

/**
* Manages PropertyDialog Open Event. Opens PropertyDialog
*/
void PictureManager::PropertyDialogOpenSlot()
{
	PropertyDialog dialog(this->itsProperty);
	dialog.exec();
}

/**
* returns itsProperty parameter
* @return Property
*/
Property* PictureManager::getItsProperty() const
{
        return itsProperty;
}
/**
* Manages Sorting Method changes Event
*/
void PictureManager::sortingMethodChangedSlot(int index)
{
	this->itsProperty->setSortMethod((Property::SortMethod)index);
	this->reLoadBrowserSlot();
}

/**
* Returns current directory
*/
QDir* PictureManager::getCurDir() const
{
        return curDir;
}
/**
* Hendles delete files Action
*/
void PictureManager::deleteFilesSlot()
{
         QMessageBox msgBox;
         msgBox.setStandardButtons(QMessageBox::No|QMessageBox::Yes);
         msgBox.setText(tr("Are you sure to delete selected files?"));
         msgBox.setWindowTitle("Deleting files...");
         msgBox.setIcon(QMessageBox::Question);
        if ( msgBox.exec()==QMessageBox::Yes ) {
           this->itsReader->setIsActive(false);  
           new FileOperationsHandler(this, FileOperationsHandler::Delete, this->fillFileList());
        }
}

/**
* Hendles copy files Action
*/
void PictureManager::copyFilesSlot()
{
        QString newDir;
        QFileDialog dialog(this);
        dialog.setDirectory(*this->getCurDir());
        dialog.setFileMode(QFileDialog::DirectoryOnly );
        if (dialog.exec()){
          newDir = dialog.directory().absolutePath ();
          new FileOperationsHandler(this, FileOperationsHandler::Copy,this->fillFileList(), newDir);
        }
}

/**
* Hendles move files Action
*/
void PictureManager::moveFilesSlot()
{
        QString newDir;
        QFileDialog dialog(this);
        dialog.setDirectory(*this->getCurDir());
        dialog.setFileMode(QFileDialog::DirectoryOnly );
        if (dialog.exec()){
          this->itsReader->setIsActive(false);
          newDir = dialog.directory().absolutePath ();
          new FileOperationsHandler(this, FileOperationsHandler::Move, this->fillFileList(), newDir);
        }
}

/**
* Handles make directory Action
*/
void PictureManager::makeDirectorySlot()
{
     bool ok;
     QString text = QInputDialog::getText(this, tr("Make new directory"), tr("Enter directory name"), QLineEdit::Normal, QDir::home().dirName(), &ok);
     if (ok && !text.isEmpty()) new FileOperationsHandler(this, FileOperationsHandler::MakeDir, this->fillFileList(), text);
}

/**
* Fill in list of selected items to copy/delete/move procedures
*/
QList<QFileInfo> PictureManager::fillFileList()
{
        QList<QFileInfo> lista;
        QList<QListWidgetItem *> selectedItemsIndex = this->getListWidget()->selectedItems ();
        if (selectedItemsIndex.count()>0) {
                QListIterator<QListWidgetItem *> iterator(selectedItemsIndex);
                iterator.toFront();
                while (iterator.hasNext()) {
                        lista.append((dynamic_cast<PictureListWidgetItem*>(iterator.next()))->getFile());
                }
        }
        return lista;
}

/**
* Returns poiter to image reader
*/
ImageReader* PictureManager::getItsReader() const
{
        return itsReader;
}








